package syb.page.temperature.plugin;

import com.zhny.aiot.plugin.ICenterFacilities;
import com.zhny.aiot.plugin.IDeviceFactory;
import com.zhny.aiot.plugin.core.model.IRequestMessage;
import com.zhny.aiot.plugin.modbus.ModemEngine;
import com.zhny.aiot.plugin.modbus.device.ModemConfig;
import com.zhny.aiot.plugin.modbus.device.modbus.ModbusNumDevice;
import com.zhny.aiot.plugin.modbus.handler.model.ModemResponseMessage;
import com.zhny.aiot.plugin.model.DeviceEntity;
import com.zhny.aiot.plugin.model.TaskEntity;
import io.netty.buffer.ByteBuf;
import syb.page.temperature.plugin.model.PageTemperatureStoreEntry;

public class PageTemperatureDevice extends ModbusNumDevice<PageTemperatureStoreEntry> {
    public PageTemperatureDevice(ModemEngine engine, IDeviceFactory<ModemConfig> factory, ICenterFacilities centerFacilities, DeviceEntity entity) {
        super (engine, factory, centerFacilities, entity);
    }

    @Override
    public PageTemperatureStoreEntry decode(ModemResponseMessage msg) {
        logger.info("start syb radiation decode");
        ByteBuf buf = msg.getData();
        int temperature = buf.readShort ();
        int humidity = buf.readUnsignedShort ();
        PageTemperatureStoreEntry entry = new PageTemperatureStoreEntry();
        entry.setTemperature (String.format ("%.1f",temperature/10.0));
        entry.setHumidity (String.format ("%.1f",humidity/10.0));
        logger.info ("{}[{}]",this.entity.getName (),entry);
        return entry;
    }

    @Override
    public boolean checkError(ModemResponseMessage modemResponseMessage) {
        return modemResponseMessage.getData().readableBytes()== 4;
    }

    @Override
    protected IRequestMessage getCommand(TaskEntity taskEntity) {
        return getFactory().getRequestMessage(getConfig());
    }

    @Override
    protected void disposable() {

    }
}
